package com.hjy.demojavamail;

import java.util.Properties;
import java.util.UUID;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.junit.Test;

public class JavaMailTest {

	@Test
	public void testJavaMail(){
		try{
			
			/**
			 * 1.建立连接对象，连接到服务器
			 */
			Properties props = new Properties();
			props.setProperty("mail.transport.protocol", "smtp");//协议
			props.setProperty("mail.smtp.host", "smtp.126.com");//主机名
			props.setProperty("mail.smtp.port", "25");//端口号
			props.setProperty("mail.smtp.auth", "true");//是否开启权限控制
			props.setProperty("mail.debug", "true");//是否打印发送时的信息
			
			Session session = Session.getInstance(props);
			
			/**
			 * 2.创建邮件对象
			 */
			Message msg = new MimeMessage(session);
			//邮件发件人
			msg.setFrom(new InternetAddress("wzyong1024@126.com","地表最强demo","utf-8"));
			//邮件标题
			msg.setSubject("地表最强demo邮箱验证");
			
			//随机生成验证码
			String code = UUID.randomUUID().toString();
			//邮件内容
			String content = "<html><head></head><body><h1>请点击连接激活</h1><h3><a href='http://localhost:8080/demo?code="
			        + code + "'>http://localhost:8080/demo?code=" + code + "</href></h3></body></html>";
			
			//设置邮件内容
			msg.setContent(content, "text/html;charset=UTF-8");
			
			//设置邮件收件人
			msg.setRecipient(Message.RecipientType.TO, new InternetAddress("395778325@qq.com","尊敬的用户","utf-8"));
			
			/**
			 * 3.创建Transport对象，发送邮件
			 */
			Transport trans = session.getTransport();
			//连接服务器
			trans.connect("wzyong1024","GBUYGSPRTZCHSYNR");
			//发送邮件
			trans.sendMessage(msg, msg.getAllRecipients());
			//关闭连接
			trans.close();
		} catch (Exception ex){
			ex.printStackTrace();
		}
	}
}
